package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.PageResult;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.ThreadLocalUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentService {


    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     *对动态发布评论
     * 就是要向数据库添加一条评论的数据，所有先用对象封装数据，然后调用api保存数据
     */

    public void postCommon(String movementId, String text) {

        //1.封装数据
        /**
         *             private ObjectId publishId;    //要评论的动态id
         *             private Integer commentType;   //评论类型，1-点赞，2-评论，3-喜欢
         *             private String content;        //评论内容
         *             private Long userId;           //评论人的id
         *             private Long publishUserId;    //被评论人ID
         *             private Long created; 		   //发表时间
         *             private Integer likeCount = 0; //当前评论的点赞数
        */

        //1.封装数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));//动态id
        comment.setCommentType(CommentType.COMMENT.getType());//评论
        comment.setContent(text);//评论的内容
        comment.setUserId(ThreadLocalUtils.getUserId());//评论人的id
        comment.setCreated(System.currentTimeMillis());
        //被评论人的id留到api层再封装
        //2.调用api保存数据
        Integer integer = commentApi.postCommen(comment);


    }


    /**
     *
     *查看评论列表
     */
    public PageResult lookComments(String movementId, Integer page, Integer pageSize) {

        //1.调用api查询评论comments集合
        List<Comment> comments = commentApi.lookComments(movementId, page, pageSize, CommentType.COMMENT.getType());
        //2.判断集合是否为空，为空则直接new PageResult返回
        if(CollUtil.isEmpty(comments)){
          return   new PageResult();
        }
        //3.获取评论人的id,查询评论人的用户详情
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.batchQueryUserInfo(userIds, null);
        //4.遍历评论集合，一个comment对象就构造一个vo对象
        List<CommentVo> commentVos = new ArrayList<>();

        for (Comment comment : comments) {
            Long id = comment.getUserId();
            UserInfo userInfo = userInfoMap.get(id);
            if(userInfo != null){
                CommentVo commentVo = CommentVo.init(userInfo, comment);
                commentVos.add(commentVo);
            }
        }
        //5.构造返回值
        PageResult pageResult = new PageResult(page,pageSize,0,commentVos);
        return pageResult;

    }


    /**
     * 动态点赞
    **/
    public Integer like(String movementId) {

        //1.判断用户是否点赞过，如果有，抛出一个异常
        Boolean result = commentApi.isLike(ThreadLocalUtils.getUserId(), movementId,CommentType.LIKE);
        //2.true代表点赞过
        if(result){
            throw new BusinessException(ErrorResult.likeError());
        }

        //3.创建comment对象封装数据，调用api保存数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));//动态id
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(ThreadLocalUtils.getUserId());//当前操作的用户id
        comment.setCreated(System.currentTimeMillis());

        Integer count = commentApi.postCommen(comment);

        //4.把点赞状态，缓存到Redis
        //存的value是hash值
        String key = Constants.MOVEMENTS_INTERACT_KEY +movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + ThreadLocalUtils.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");

        return count;
    }

    /**
     *取消点赞
     */
    public Integer disLikeComment(String movementId) {

        //1.判断用户是否已经点赞过
        Boolean result = commentApi.isLike(ThreadLocalUtils.getUserId(),movementId,CommentType.LIKE);
        //2.如果没点赞过，抛出一个异常
        if(!result){
            //true代表点赞过
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3.封装要删除的数据，调用api删除
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(ThreadLocalUtils.getUserId());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());

        Integer count = commentApi.delete(comment);

        //4.删除redis缓存的点赞状态

        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + ThreadLocalUtils.getUserId();

        redisTemplate.opsForHash().delete(key, hashKey);

        return count;
    }


    /**
     *
     * 动态喜欢
     */
    public Integer saveLoveMovement(String movementId) {
        //1.判断用户是否点过喜欢，点过之后就不可以再点了；其实际就是查询comment表有没有数据
       Boolean result = commentApi.isLike(ThreadLocalUtils.getUserId(),movementId,CommentType.LOVE);

        //2.用户点过喜欢，抛出一个异常

        if(result){
            //true代表用户已喜欢
            throw new BusinessException(ErrorResult.loveError());
        }
        //3.封装数据，调用api保存数据

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(ThreadLocalUtils.getUserId());
        comment.setCreated(System.currentTimeMillis());

        Integer count = commentApi.postCommen(comment);
        //4.把喜欢的状态缓存至redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getPublishId();
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + ThreadLocalUtils.getUserId();
        redisTemplate.opsForHash().hasKey(key, hashKey);


        return count;
    }

    /**
     *取消喜欢
     */
    public Integer unLOve(String movementId) {
    //2.判断用户有没有喜欢过，没有喜欢过不能取消喜欢
        Boolean result = commentApi.isLike(ThreadLocalUtils.getUserId(), movementId, CommentType.LOVE);

        if(!result){
            throw new BusinessException(ErrorResult.disloveError());
        }

        //2.封装要删除的数据，调用api删除数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(ThreadLocalUtils.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);
        //3.删除redis缓存的喜欢状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getPublishId();
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + ThreadLocalUtils.getUserId();

        redisTemplate.opsForHash().delete(key, hashKey);

        return count;
    }


    /**
     * 对评论点赞
     * @param commentId
     * @return
     *//*
    public Integer likeComment(String commentId) {

        //1.判断用户对评论是否已经点过赞
        //635d60af18bd961c0e51e61b
        Boolean result = commentApi.hasLikeComment(ThreadLocalUtils.getUserId(),commentId,CommentType.LIKE);

        if(result){
            //已经点赞
            throw new BusinessException(ErrorResult.likeError());
        }

        //当前他传过来的是要点赞的评论id，


        Comment comment = new Comment();
       // comment.setId(new ObjectId(commentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(ThreadLocalUtils.getUserId());
        comment.setCreated(System.currentTimeMillis());

        //保存对评论点赞的数据内容到数据库
       Integer count = commentApi.saveLikeComment(comment);

     *//*   //3.把点赞状态缓存进redis里
        String key = Constants.MOVEMENTS_INTERACT_KEY+commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY +ThreadLocalUtils.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");*//*

        return count;

    }*/



    /*
    *//**
     * 取消对评论的点赞
     * @param commentId
     * @return
     *//*
    public Integer disLike(String commentId) {

        //1.判断用户是否点赞了。没有点赞怎么会可以取消点赞呢
        Boolean result = commentApi.hasLikeComment(ThreadLocalUtils.getUserId(), commentId,CommentType.LIKE);

        if(!result){
            //用户没有点赞了，不可以取消点赞
            throw  new BusinessException(ErrorResult.disLikeError());
        }
        //2。封装要删除的数据
        Comment comment = new Comment();
        comment.setId(new ObjectId(commentId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(ThreadLocalUtils.getUserId());
        comment.setCreated(System.currentTimeMillis());


        Integer count = commentApi.deleteLikeComment(comment);

        //3.删除redis缓存的对评论点赞的状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + ThreadLocalUtils.getUserId();

        redisTemplate.opsForHash().delete(key, hashKey);


        return count;
    }*/
}
